#!/usr/bin/python
import time
import RPi.GPIO as GPIO
import serial
import sys

# Zuordnung der GPIO Pins (ggf. anpassen)
TXD = 14
RXD = 15

E_PULSE = 0.00005
E_DELAY = 0.00005

UART_READY = 		"A3"
SLCD_INIT_ACK =		"A5"
SLCD_CONTROL_HEADER = 	"9F"
SLCD_CONTROL_HEADER =	"9F"
SLCD_CHAR_HEADER =	"FE"
SLCD_CURSOR_HEADER =	"FF"
SLCD_CURSOR_ACK =	"5A"
SLCD_RETURN_HOME =	"61"
SLCD_DISPLAY_OFF =	"63"
SLCD_DISPLAY_ON =	"64"
SLCD_CLEAR_DISPLAY =	"65"
SLCD_CURSOR_OFF =	"66"
SLCD_CURSOR_ON =	"67"
SLCD_BLINK_OFF =	"68"
SLCD_BLINK_ON =		"69"
SLCD_SCROLL_LEFT =	"6C"
SLCD_SCROLL_RIGHT =	"72"
SLCD_NO_AUTO_SCROLL =	"6A"
SLCD_AUTO_SCROLL =	"6D"
SLCD_LEFT_TO_RIGHT =	"70"
SLCD_RIGHT_TO_LEFT =	"71"
### Firmware 1.0b and above ###
SLCD_BACKLIGHT_ON =	"81"
SLCD_BACKLIGHT_OFF =	"80"
SLCD_POWER_ON =   	"83"
SLCD_POWER_OFF = 	"82"

def main():
	
	
	serialport.open()
	display_init(serialport)
	time.sleep(E_DELAY)
	display_write(serialport, "na")
	serialport.close()
	

def display_init():
	serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
	time.sleep(0.1)
	display_cmd(serialport, SLCD_POWER_ON)
	display_cmd(serialport, SLCD_INIT_ACK)
	display_cmd(serialport, SLCD_CURSOR_ON)
	display_cmd(serialport, SLCD_SCROLL_LEFT)
	display_cmd(serialport, SLCD_LEFT_TO_RIGHT)
	display_cmd(serialport, SLCD_CLEAR_DISPLAY)
	display_cmd(serialport, SLCD_RETURN_HOME)
	display_cmd(serialport, SLCD_BACKLIGHT_ON)
	time.sleep(0.1)
    return serialport


def display_cmd(serialport, cmd):
	serialport.write(cmd.decode("hex"))
	time.sleep(0.1)
	serialport.flush()
	
	
def display_write(serialport, string):
	display_cmd(serialport, SLCD_CONTROL_HEADER)
	display_cmd(serialport, SLCD_CLEAR_DISPLAY)
	display_cmd(serialport, SLCD_CHAR_HEADER) 
	serialport.write(string)
	time.sleep(0.1)	

if __name__ == '__main__':
	main()
